from zope.interface import Interface, implements
from zope import schema
from zope.formlib import form
from plone.app.controlpanel.form import ControlPanelForm
from Products.CMFDefault.formlib.schema import SchemaAdapterBase
from zope.component import adapts
from zope.component import getUtility
from zope.schema.vocabulary import SimpleTerm, SimpleVocabulary
from Products.CMFPlone.interfaces import IPloneSiteRoot
from Products.CMFCore.interfaces import IPropertiesTool
from plone.app.viewletmanager.interfaces import IViewletSettingsStorage

from plone.protect import CheckAuthenticator
from zope.event import notify
from plone.app.controlpanel.events import ConfigurationChangedEvent
from plone.app.form.validators import null_validator

from polygonstudio.marvin import config
from polygonstudio.marvin import marvinMessageFactory as _
from Products.CMFPlone import PloneMessageFactory as _p

from Products.CMFPlone.utils import safe_unicode

class IMarvinConfigurationSchema(Interface):
    # -*- extra stuff goes here -*-
    tmdbAPIKey = schema.TextLine(
                                    title=_(u'The Movie DB - API Key'),
				)
    tmdbLanguage = schema.TextLine(
                                    title=_(u'The Movie DB - prefered Language'),
				)

class MarvinControlPanelAdapter(SchemaAdapterBase):
    """ Control Panel adapter """

    adapts(IPloneSiteRoot)
    implements(IMarvinConfigurationSchema)

    def __init__(self, context):
        super(MarvinControlPanelAdapter, self).__init__(context)
        pprop = getUtility(IPropertiesTool)
        self.polygonstudio_marvin_props = getattr(pprop, 'polygonstudio_marvin_properties', None)
	self.portal_props = getattr(pprop, 'portal_properties', None)
	self.encoding = self.portal_props.site_properties.default_charset
	self.context = context

    def viewletVisible(self, manager, viewlet):
        storage = getUtility(IViewletSettingsStorage)
        skinname = self.context.getCurrentSkinName()
        hidden = storage.getHidden(manager, skinname)
        return viewlet not in hidden

    def setViewletVisibility(self, manager, viewlet, visible):
        storage = getUtility(IViewletSettingsStorage)
        skinname = self.context.getCurrentSkinName()
        hidden = storage.getHidden(manager, skinname)
        if visible:
            # viewlet should be visible
            if viewlet in hidden:
                hidden = tuple(x for x in hidden if x != viewlet)
        else:
            # hide viewlet
            if viewlet not in hidden:
                hidden = hidden + (viewlet,)
        storage.setHidden(manager, skinname, hidden)
        # hide viewlet in default skin as well
        default = storage.getDefault(manager)
        if (default is not None) and default != skinname:
            storage.setHidden(manager, default, hidden)

    def get_tmdbAPIKey(self):
        return safe_unicode(self.polygonstudio_marvin_props.tmdbAPIKey)

    def set_tmdbAPIKey(self, tmdbAPIKey):
	self.polygonstudio_marvin_props.tmdbAPIKey = tmdbAPIKey.encode(self.encoding)

    def get_tmdbLanguage(self):
        return safe_unicode(self.polygonstudio_marvin_props.tmdbLanguage)

    def set_tmdbLanguage(self, tmdbLanguage):
        self.polygonstudio_marvin_props.tmdbLanguage = tmdbLanguage.encode(self.encoding)

    tmdbAPIKey = property(get_tmdbAPIKey, set_tmdbAPIKey)
    tmdbLanguage = property(get_tmdbLanguage, set_tmdbLanguage)

class MarvinConfiguration(ControlPanelForm):
    implements(IMarvinConfigurationSchema)
    form_fields = form.FormFields(IMarvinConfigurationSchema)
    label = _(u'polygonstudio - Marvin Configuration')
    description = _(u'configuration configuration for polygonstudio.marvin')

    @form.action(_p(u'label_save', default=u'Save'), name=u'save')
    def handle_edit_action(self, action, data):
        CheckAuthenticator(self.request)
        if form.applyChanges(self.context, self.form_fields, data,
                             self.adapters):
            self.status = _p("Changes saved.")
            notify(ConfigurationChangedEvent(self, data))
            self._on_save(data)
        else:
            self.status = _p("No changes made.")

    @form.action(_p(u'label_cancel', default=u'Cancel'),
                 validator=null_validator,
                 name=u'cancel')
    def handle_cancel_action(self, action, data):
        IStatusMessage(self.request).addStatusMessage(_p("Changes canceled."),
                                                      type="info")
        url = getMultiAdapter((self.context, self.request),
                              name='absolute_url')()
        self.request.response.redirect(url + '/plone_control_panel')
        return ''

